<style>
  #map {
    width: 100%;
    height: 100vh;
  }
  #slider {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 50%;
    width: 4px;
    background: #fff;
    z-index: 10;
    cursor: ew-resize;
  }
</style>

<div id="map"></div>
<div id="slider"></div>

<script type="module">
  import Map from 'ol/Map';
  import View from 'ol/View';
  import TileLayer from 'ol/layer/Tile';
  import OSM from 'ol/source/OSM';
  import XYZ from 'ol/source/XYZ';
  import { fromLonLat } from 'ol/proj';

  let swipe = 0.5;

  const baseLayer = new TileLayer({
    source: new OSM()
  });

  const compareLayer = new TileLayer({
    source: new XYZ({
      url: 'https://{a-c}.tile.opentopomap.org/{z}/{x}/{y}.png'
    })
  });

  compareLayer.on('prerender', function (event) {
    const ctx = event.context;
    const width = ctx.canvas.width * swipe;
    ctx.save();
    ctx.beginPath();
    ctx.rect(0, 0, width, ctx.canvas.height);
    ctx.clip();
  });

  compareLayer.on('postrender', function (event) {
    event.context.restore();
  });

  const map = new Map({
    target: 'map',
    layers: [baseLayer, compareLayer],
    view: new View({
      center: fromLonLat([0, 0]),
      zoom: 2,
    })
  });

  const slider = document.getElementById('slider');

  slider.addEventListener('mousedown', () => {
    function move(e) {
      swipe = e.clientX / window.innerWidth;
      map.render(); // 重新渲染
      slider.style.left = `${e.clientX}px`;
    }

    function up() {
      window.removeEventListener('mousemove', move);
      window.removeEventListener('mouseup', up);
    }

    window.addEventListener('mousemove', move);
    window.addEventListener('mouseup', up);
  });
</script>
